import datetime
import multiprocessing


def calc(num):
    sum = 0
    # 1到1亿的加法
    for i in range(num):
        sum += i
    return sum


if __name__ == '__main__':
    start = datetime.datetime.now()
    # 使用5个进程同时跑
    lst = []
    for _ in range(5):
        t = multiprocessing.Process(target=calc, args=(100000000,))
        t.start()
        lst.append(t)

    for t in lst:
        t.join()

    end = (datetime.datetime.now() - start).total_seconds()
    print(end)

"""
针对上面代码进行改进：
"""
import datetime
import multiprocessing


def calc(num):
    sum = 0
    for i in range(num):
        sum += i
    return sum


if __name__ == '__main__':
    start = datetime.datetime.now()
    # 实例化一个线程池。
    p = multiprocessing.Pool(5)
    # 异步模式从线程池中拿走5个线程资源
    for i in range(5):
        p.apply_async(calc, args=(i,))

    # join之前必须close
    p.close()
    p.join()

    end = (datetime.datetime.now() - start).total_seconds()
    print(end)
